package com.qianfeng.gl4study.youshare.model;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * 存储商品分类的类
 * Created with IntelliJ IDEA.
 * I'm glad to share my knowledge with you all.
 * User:Gaolei
 * Date:2015/2/6
 * Email:pdsfgl@live.com
 */
public class Category {
	/*
	  "id": "4",
      "name": "女鞋箱包",
      "url": "category.php?id=4",
	 */

	private String id;
	private String name;
	private String url;
	private List<Category> subCategories;

	public List<Category> getSubCategories() {
		return subCategories;
	}

	public Category(){
		subCategories = new LinkedList<Category>();
	}

	public String getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public String getUrl() {
		return url;
	}

	public List<Category> getSunCategory(){
		return subCategories;
	}
	public void parseJSON(JSONObject json){
		if(json!=null){
			try {
				id = json.getString("id");
				name = json.getString("name");
				url = json.getString("url");

				try {
					//存在子分类，对子分类进行解析。不存在忽略异常信息即可。
					JSONObject jsonObject = json.getJSONObject("cat_id");
					JSONArray names = jsonObject.names();
					if(names!=null){
						int length = names.length();
						for (int i = 0; i < length; i++) {
							String string = names.getString(i);
							JSONObject object = jsonObject.getJSONObject(string);
							Category category = new Category();
							category.parseJSON(object);
							subCategories.add(category);
						}
					}
				}catch (JSONException e) {
					//忽略异常信息
					e.printStackTrace();
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
}
